var express = require("express");
var url = require("url");
var mysql = require("mysql");
var expressStatic = require("express-static");
var ejs = require("ejs");
var server = express();
var port = 8081;

var sql = mysql.createConnection({
	host:"localhost",
	user:"root",
	password:"admin",
	database:"movie"
})

sql.connect();

server.get("/",(request,response)=>{
	var hot = 0;
	var jijiang = 0;
	sql.query(`select name,score,img,url,status from movie where status="1"`,(error,data)=>{
		hot = data;
		sql.query(`select name,score,img,url,status from movie where status="0"`,(error,data)=>{
			jijiang = data;
			if(error){
				console.log(error)
				response.end("查找数据库错误");
			}
			else{
				ejs.renderFile("static/index.html",{data:{hot:hot,jijiang:jijiang}},(error,result)=>{
					if(error){
						response.end("解析错误");
						console.log(error)
					}
					else{
						response.end(result)
					}
				})
			}
		})
	})
})

server.get("/movie",(request,response)=>{
	var id = url.parse(request.url,true).query.id;
	sql.query(`select * from movie where url="${id}"`,(error,data)=>{
		if(error){
			console.log(error);
			response.end("数据库查询错误")
		}
		else{
			ejs.renderFile("static/minute.html",{data:data[0]},(error,result)=>{
				if(error){
					console.log(error)
					response.end("解析失败")
				}
				else{
					response.end(result)
				}
			})
		}
	})
})

server.get("/movielist",(request,response)=>{
	sql.query(`select * from movie`,(error,data)=>{
		if(error){
			console.log(error);
			response.end("数据库查询错误")
		}
		else{
			ejs.renderFile("static/movie.html",{data:data},(error,result)=>{
				console.log(data)
				if(error){
					console.log(error)
					response.end("解析失败")
				}
				else{
					response.end(result)
				}
			})
		}
	})
})


server.use(expressStatic(__dirname + "/static"));
server.listen(port);
console.log(`server is at ${port}`)